<template>
  <div class="login-container">
    <el-card class="login-box">
      <h2>门诊预约系统登录</h2>
      <div class="nav-links">
        <el-link type="primary" @click="goHome">返回首页</el-link>
      </div>
      <el-form
          :model="form"
          :rules="rules"
          ref="loginForm"
          @submit.prevent="handleLogin">

        <el-form-item prop="username">
          <el-input
              v-model="form.username"
              placeholder="请输入用户名"
              prefix-icon="User"
          />
        </el-form-item>

        <el-form-item prop="password">
          <el-input
              v-model="form.password"
              type="password"
              placeholder="请输入密码"
              prefix-icon="Lock"
          />
        </el-form-item>

        <el-form-item prop="role">
          <el-radio-group v-model="form.type">
            <el-radio label=2>患者</el-radio>
            <el-radio label=1>医生</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-button
            type="primary"
            native-type="submit"
            class="login-btn">
          登录
        </el-button>
        <div class="register-link">
          没有账号？<el-link type="primary" @click="goRegister">立即注册</el-link>
        </div>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import {userLogin} from "@/api/user.js";
import {setAuth, setUserInfo} from "@/utils/auth.js";

const router = useRouter();

const form = ref({
  username: '',
  password: '',
  type: 2
});

const rules = {
  username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
  type: [{ required: true, message: '请选择角色', trigger: 'change' }]
};

const handleLogin = async () => {
  try {
    form.value.type = Number(form.value.type);
    const res = await userLogin(form.value);
    if (res.data.user !== null) {
      setAuth(res.data.token);
      setUserInfo(res.data.user);
      ElMessage.success('登录成功');
      await router.push('/home');
    }
    if (res.data.doctor !== null) {
      setAuth(res.data.token);
      setUserInfo(res.data.doctor);
      ElMessage.success('登录成功');
      await router.push('/doctor/appointments');
    }
  } catch (error) {
    ElMessage.error(error.message);
  }
};

const goRegister = () => {
  router.push('/register');
};

const goHome = () => {
  router.push('/home');
};
</script>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  background: #f0f2f5;
}
.login-box {
  width: 400px;
  padding: 20px;
}
.login-btn {
  width: 100%;
}

.register-link {
  margin-top: 15px;
  text-align: center;
  color: #606266;
}

.nav-links {
  margin-bottom: 15px;
  text-align: center;
}
</style>
